package com.tucue.controller;

import com.tucue.dao.*;
import com.tucue.model.*;
import com.tucue.utils.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@Controller
@RequestMapping("/add")
public class AddController extends BaseController{

    //新建资讯
    @RequestMapping(value="/news", method = RequestMethod.POST)
    public String addNews(@ModelAttribute @Valid News news, BindingResult result,HttpServletRequest request,@RequestParam MultipartFile[] file,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try {
            news.setCreatetime(getCurrentTimeStamp());
            news.setUpdatetime(getCurrentTimeStamp());
            news.setPublishtime(getCurrentTimeStamp());
            news.setStatus(Constant.RECORD_STATUS_INDEX3);
            news.setUserid(getCurrentUser(session).getUserid());
            news.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            news.setUserid(getCurrentUser(session).getUserid());
            news.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            this.getSqlSession();
            NewsMapper mapper=sqlSession.getMapper(NewsMapper.class);
            mapper.insert(news);
            sqlSession.commit();
            //插入日志记录
            createLog(request,"news", news.getNewsid());
            insertFile(file,request,"activity",news.getNewsid());
            return "redirect:/query/parkQueryNews";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        } finally {
            this.closeSqlSession();
        }
    }

    //  用户新建
    @RequestMapping(value="/user", method = RequestMethod.POST)
    public String  addUser(@ModelAttribute @Valid User user, BindingResult result,HttpServletRequest request) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try {
            this.getSqlSession();
            UserMapper mapper=sqlSession.getMapper(UserMapper.class);
            user.setStatus(Constant.RECORD_STATUS_INDEX3);
            mapper.insert(user);
            sqlSession.commit();
            //插入用户模块关联表记录
//            String[] checkBoxArgs=request.getParameterValues("moduleId");
//            for(int i=0;i<checkBoxArgs.length;i++){
//                usermodule(user);
//            }
            return "redirect:/query/appUserSetting";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        } finally {
            this.closeSqlSession();
        }
    }

    //    园区活动 天使有约活动新建
    @RequestMapping(value="/Activity", method = RequestMethod.POST)
    public String   parkActivity(@ModelAttribute @Valid Activity act,BindingResult result,@RequestParam String categoryStr,HttpServletRequest request,@RequestParam MultipartFile[] files,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            ActivityMapper activityMapper=sqlSession.getMapper(ActivityMapper.class);

            if(act.getNeedcheck()==null){
                act.setNeedcheck(0);
            }
            act.setVisible(1);
            act.setEnddatetime(getDateTime(request,"enddatetime"));

            act.setStatus(Constant.RECORD_STATUS_INDEX3);
            act.setCategory(Integer.parseInt(categoryStr));
            act.setCreatetime(getCurrentTimeStamp());
            act.setUserid(getUserId(session));
            activityMapper.insert(act);
            sqlSession.commit();
            //插入附件
            insertFile(files,request,"activity",1);
            //插入日志记录
            createLog(request, "activity", act.getActivityid());

            if(categoryStr.equals("1")){
                return "redirect:/query/parkQueryActivity";
            }else{
                return "redirect:/query/appQueryActivity";
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }
        finally {
            this.closeSqlSession();
        }
    }

    //    园区新建
    @RequestMapping(value="/park", method = RequestMethod.POST)
    public String addPark(@ModelAttribute @Valid Park park, BindingResult result,@RequestParam MultipartFile[] files,HttpServletRequest request) {

        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            ParkMapper parkMapper=sqlSession.getMapper(ParkMapper.class);
            park.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            park.setStatus(Constant.RECORD_STATUS_INDEX3);
            park.setCreatetime(getCurrentTimeStamp());

            parkMapper.insert(park);
            sqlSession.commit();
            insertFile(files,request,"park",park.getParkid());
            return "redirect:/query/appGargen";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        } finally {
            this.closeSqlSession();
        }
    }

    //????需啊哟返回页面吗天使有约活动简介 关于 接入平台 用户协议新建/编辑
    @RequestMapping("/simpleTable")
    public String addSimple(@ModelAttribute @Valid SimpleTable simpleTable, BindingResult result,@RequestParam String categoryStr) {
        System.out.print("不应该");
        if(result.hasErrors()) {
            printError(result);
        }

        try{
            this.getSqlSession();
            SimpleTableMapper simpleTableMapper=sqlSession.getMapper(SimpleTableMapper.class);
            simpleTable.setCategory(Integer.parseInt(categoryStr));

            simpleTableMapper.insert(simpleTable);
            sqlSession.commit();
            return getSuccessPage();
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }
        finally {
            this.closeSqlSession();
        }
    }

    //app政策新建
    @RequestMapping("/appPolicy")
    public String  policy(@ModelAttribute @Valid AppPolicy appPolicy, BindingResult result,HttpServletRequest request,@RequestParam MultipartFile[] files) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            appPolicy.setCreatetime(getCurrentTimeStamp());
            appPolicy.setStatus(Constant.RECORD_STATUS_INDEX3);
            appPolicy.setVisible("1");
            AppPolicyMapper appPolicyMapper=sqlSession.getMapper(AppPolicyMapper.class);
            appPolicyMapper.insert(appPolicy);
            sqlSession.commit();

            //实施区域关联记录
            String[] checkBoxArgs=request.getParameterValues("regionId");
            for(int i=0;i<checkBoxArgs.length;i++){
//                itemRegion(appPolicy.getApppolicyid(), checkBoxArgs[i],1);
            }
            //插入日志记录
            createLog(request, "apppolicy", appPolicy.getApppolicyid());
            //上传附件
            insertFile(files,request,"apppolicy",appPolicy.getApppolicyid());
            return "redirect:/query/appPolicy";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //投资服务产品新建
    @RequestMapping("/appInvest")
    public String invest(@ModelAttribute @Valid InvestmentService investmentService, BindingResult result,HttpServletRequest request,@RequestParam MultipartFile[] files) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            investmentService.setCreatetime(getCurrentTimeStamp());
            investmentService.setStatus(Constant.RECORD_STATUS_INDEX3);
            investmentService.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            InvestmentServiceMapper investmentServiceMapper=sqlSession.getMapper(InvestmentServiceMapper.class);
            investmentServiceMapper.insert(investmentService);
            sqlSession.commit();
            //插入日志记录
            createLog(request,"investmentservice",investmentService.getInvestserviceid());
            //上传logo和附件
            insertFile(files,request,"investmentservice",investmentService.getInvestserviceid());
            return "redirect:/query/investService";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //贷款服务产品新建
    @RequestMapping("/loan")
    public String  loan(LoanService loanService,BindingResult result,HttpServletRequest request,@RequestParam MultipartFile[] files,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            loanService.setCreatetime(geStringTimeStamp());
            loanService.setStatus(Constant.RECORD_STATUS_INDEX3);
            loanService.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            loanService.setUserid(getUserId(session));
            LoanServiceMapper loanServiceMapper=sqlSession.getMapper(LoanServiceMapper.class);
            loanServiceMapper.insert(loanService);
            sqlSession.commit();
            //插入日志记录
            createLog(request,"loanservice",loanService.getLoanserviceid());
            //上传logo和附件
            insertFile(files,request,"loanervice",loanService.getLoanserviceid());
            return "redirect:/query/loanService";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //常见问题新建s
    @RequestMapping("/faq")
    public String  faq(Faq faq,BindingResult result,HttpServletRequest request) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            faq.setCreatetime(getCurrentTimeStamp());
            faq.setStatus(Constant.RECORD_STATUS_INDEX3);
            faq.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            FaqMapper faqMapper=sqlSession.getMapper(FaqMapper.class);
            faqMapper.insert(faq);
            sqlSession.commit();
            //插入日志记录
            createLog(request,"faq",faq.getFaqid());
            return "redirect:/query/appProblem";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //服务提供商新建  for语句
    @RequestMapping("/provider")
    public String  provider(ServiceProvider serviceProvider,BindingResult result,HttpServletRequest request,@RequestParam MultipartFile[] files) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            serviceProvider.setCreatetime(geStringTimeStamp());
            serviceProvider.setStatus(Constant.RECORD_STATUS_INDEX3);
            serviceProvider.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            ServiceProviderMapper serviceProviderMapper=sqlSession.getMapper(ServiceProviderMapper.class);
            serviceProviderMapper.insert(serviceProvider);
            sqlSession.commit();

            //复选框素数组
            String[] checkBoxArgs=request.getParameterValues("productId");
            //服务提供商id
            int id=serviceProvider.getServiceproviderid();

//  !!!!!查询前端还没实现？
//            for(int i=0;i<checkBoxArgs.length;i++) {
//                if (checkBoxArgs[i] == "1") {
//                    createService(id, checkBoxArgs[i], 1);
//                } else if(checkBoxArgs[i] == "2") {
//                    createService(id, checkBoxArgs[i], 2);
//                } else if(checkBoxArgs[i] == "3") {
//                    createService(id, checkBoxArgs[i], 3);
//                }
//            }
            //插入日志记录
            createLog(request, "serviceprovider", serviceProvider.getServiceproviderid());
            //上传附件
            insertFile(files,request,"serviceprovider",serviceProvider.getServiceproviderid());
            return "redirect:/query/appServer";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //通用服务产品新建
    @RequestMapping("/general")
    public String  general(GeneralService generalService,BindingResult result,HttpServletRequest request,@RequestParam MultipartFile[] files,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            generalService.setCreatetime(getCurrentTimeStamp());
            generalService.setStatus(Constant.RECORD_STATUS_INDEX3);
            generalService.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            generalService.setUserid(getUserId(session));
            GeneralServiceMapper generalServiceMapper=sqlSession.getMapper(GeneralServiceMapper.class);
            generalServiceMapper.insert(generalService);
            sqlSession.commit();
            //插入日志记录
            createLog(request,"generalservice",generalService.getGeneralserviceid());
            //上传附件
            insertFile(files,request,"generalservice",generalService.getGeneralserviceid());
           return "redirect:/query/generalService";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //招商政策新建
    @RequestMapping("/merchantsPolicy")
    public String  merchantsPolicy(MerchantsPolicy merchantsPolicy,BindingResult result,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            merchantsPolicy.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            merchantsPolicy.setStatus(Constant.RECORD_STATUS_INDEX3);
            //若此账户没有parkid的话就不能添加招商政策
            int parkID=((User)session.getAttribute("userInSession")).getParkid();
            merchantsPolicy.setParkid(parkID);
            MerchantsPolicyMapper merchantsPolicyMapper=sqlSession.getMapper(MerchantsPolicyMapper.class);
            merchantsPolicyMapper.insert(merchantsPolicy);
            sqlSession.commit();
            return "redirect:/query/parkPolicyManage";
        } catch (Exception ex) {
            ex.printStackTrace();
            return  getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //园区、app咨询内容新建
    @RequestMapping("/consultancy")
    public String consultancy(Consult consult,BindingResult result,HttpServletRequest request,@RequestParam String contentType) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();
            //插入咨询记录
            consult.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            consult.setStatus(Constant.RECORD_STATUS_INDEX3);
            consult.setCreatetime(getCurrentTimeStamp());
            consult.setHandletime(getDateTime(request,"handletimes"));
            consult.setContenttype(contentType);
            consult.setParentid(0);
            ConsultMapper consultMapper=sqlSession.getMapper(ConsultMapper.class);
            consultMapper.insert(consult);
            sqlSession.commit();

            //插入回复记录
            Consult consultreply =new Consult();
            consultreply.setParentid(consult.getConsultid());
            consult.setContenttype(contentType);
            consultreply.setStatus(Constant.RECORD_STATUS_INDEX3);
            consultreply.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            consultreply.setCreatetime(getCurrentTimeStamp());
            consult.setHandletime(getDateTime(request, "handletimes"));
            consultreply.setContent(request.getParameter("replyContent"));
            consultMapper.insert(consultreply);
            sqlSession.commit();
            return "redirect:/query/appConsultancy";
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }


    //招商订单新建   app端
    @RequestMapping("/merchantsOrder")
    public String merchantsOrder(MerchantsOrder merchantsOrder,BindingResult result,HttpServletRequest request,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();

            merchantsOrder.setUserid(getUserId(session));
            merchantsOrder.setParkid(Integer.parseInt(session.getAttribute("parkid").toString()));
            merchantsOrder.setCreatetime(getCurrentTimeStamp());

            MerchantsOrderMapper merchantsOrderMapper=sqlSession.getMapper(MerchantsOrderMapper.class);
            merchantsOrderMapper.insert(merchantsOrder);
            sqlSession.commit();

            orderStatus(merchantsOrder.getMerchantsorderid(),merchantsOrder.getUserid(),1);
            return getSuccessPage();
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //首页轮换图
    @RequestMapping("/slideImg")
    public String slideImg(@RequestParam MultipartFile[] files,HttpServletRequest request,BindingResult result) {
        if (result.hasErrors()) {
            printErros(result);
        }
        try {
            this.getSqlSession();
            insertFile(files, request, "首页轮换图", 1);
            return getSuccessPage();
        } catch (Exception e) {
            return "error";
        } finally {
            this.closeSqlSession();
        }
    }


   // ______________________________________________________________________________________________________________________________________________



    //服务订单新建   app端
    @RequestMapping("/ServiceOrder")
    public String ServiceOrder(ServiceOrder serviceOrder,BindingResult result,HttpServletRequest request,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }

        try{
            this.getSqlSession();

            serviceOrder.setUserid(getUserId(session));
            serviceOrder.setCreatetime(getCurrentTimeStamp());
            serviceOrder.setVisible(Constant.RECORD_VISIBLE_INDEX1);
            ServiceOrderMapper serviceOrderMapper=sqlSession.getMapper(ServiceOrderMapper.class);
            serviceOrderMapper.insert(serviceOrder);
            sqlSession.commit();
            orderStatus(serviceOrder.getServiceorderid(),serviceOrder.getUserid(),2);      //服务订单没对应数字？
            return getSuccessPage();
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //活动申请新建   app端
    @RequestMapping("/activityApply")
    public String activityApply(ActivityApply activityApply,BindingResult result,HttpServletRequest request,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }
        try{
            this.getSqlSession();

            activityApply.setUserid(getUserId(session));
            activityApply.setVisible(Constant.RECORD_VISIBLE_INDEX1);

            ActivityApplyMapper activityApplyMapper=sqlSession.getMapper(ActivityApplyMapper.class);
            activityApplyMapper.insert(activityApply);

            sqlSession.commit();
            return getSuccessPage();
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    //建议与反馈新建   app端
    @RequestMapping("/suggestionfeedback")
    public String suggestionfeedback(SuggestionFeedback suggestionFeedback,BindingResult result,HttpServletRequest request,HttpSession session) {
        if(result.hasErrors()) {
            printErros(result);
        }
        try{
            this.getSqlSession();
            suggestionFeedback.setUserid(getUserId(session));
            SuggestionFeedbackMapper suggestionFeedbackMapper=sqlSession.getMapper(SuggestionFeedbackMapper.class);
            suggestionFeedbackMapper.insert(suggestionFeedback);

            sqlSession.commit();
            return getSuccessPage();
        } catch (Exception ex) {
            ex.printStackTrace();
            return getErrorPage();
        }  finally {
            this.closeSqlSession();
        }
    }

    @RequestMapping("/login")
    public String login(ModelMap model,HttpServletRequest request) {
        this.getSqlSession();
        String email=request.getParameter("email").trim();
        System.out.print(email);
        String password=request.getParameter("password").trim();
        System.out.print(password);
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User userInSession=userMapper.selectByEmail(email);
        if(userInSession!=null){

            if(userInSession.getPassword().equals(password)){
                HttpSession session = request.getSession();
                session.setAttribute("userInSession", userInSession); //session对象中创建一个userInSession属性，指向另一个对象userInSession的存储空间
                return "index";
            }else{
                model.addAttribute("errorPassword", "您输入的面密码错误！");
                return "login";
            }
        }else
            model.addAttribute("errorEmail", "您输入的邮箱不存在！");
        return "login";
    }
}

